import 'dart:math';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_ahj_app/base/utils/screen_util.dart';
import 'package:flutter_ahj_app/base/values/SQColor.dart';

class DashBoardTablePainter {
  Size size = new Size(250.0, 250.0);
  PictureRecorder _recorder;

  DashBoardTablePainter();

  int _totalNumberSplitCircles = 100;

  ///将圆分割多少份
  int _lineWidth = 5;

  ///直线的长度
  ///
  Paint paintMain; // 显示更改率的画笔（针）
  Paint paintZhen; // 仪表盘的针
  double number_text;
  String _text;
  String _jige;
  Canvas canvas;
  Picture getBackGround(double number, String text, String jiege) {
    paintMain = new Paint();

    if ("0" == jiege) {
      paintMain.color = Color(0xffFA5050);
    } else {
      paintMain.color = SQColor.theme_color;
    }
    paintMain.strokeWidth = 20;

    ///颜色
    paintMain.style = PaintingStyle.fill;

    paintZhen = new Paint();

    if ("0" == jiege) {
      paintZhen.color = Color(0xffFA5050);
    } else {
      paintZhen.color = SQColor.theme_color;
    }

    paintZhen.strokeWidth = 20;

    ///颜色
    paintZhen.style = PaintingStyle.fill;
    number_text = number;
    _text = text;
    _jige = jiege;

    _recorder = PictureRecorder();
    canvas = Canvas(_recorder);
    canvas.clipRect(new Rect.fromLTWH(0.0, 0.0, size.width, size.height));
    drawTable(canvas, size);
    drawWords(canvas, size);

    return _recorder.endRecording();
  }

  ///画仪表盘的表格
  void drawTable(Canvas canvas, Size size) {
    double halfWidth = size.width / 2;
    double halfHeight = size.width / 2;
    canvas.translate(halfWidth, halfHeight);

    ///中间的竖线
    canvas.save();
    drawLongLine(canvas, paintZhen, halfHeight);
    canvas.restore();

    /// 保存之前的绘制内容 与 canvas.restore() 成对出现
    ///右边部分 中间竖线 和 右边最后一个横线之间的部分 分成 10分
    canvas.save();
    for (int i = 0; i < _totalNumberSplitCircles; i = i + 1) {
      canvas.rotate((pi) / (_totalNumberSplitCircles / 2));
      drawLongLine(canvas, paintZhen, halfHeight);
    }
    canvas.restore();
    canvas.save();
    if (number_text != null) {
      for (double i = 0; i < number_text; i = i + 1) {
        if (i != 0) {
          canvas.rotate((pi) / (_totalNumberSplitCircles / 2));

          ///旋转
        }
        drawLongLine(canvas, paintMain, halfHeight);
      }
    }

    canvas.restore();
    canvas.save();
  }

  ///画仪表盘上的长线
  void drawLongLine(Canvas canvas, Paint paintMain, double halfHeight) {
    canvas.drawLine(new Offset(-halfHeight, 0.0),
        new Offset(-halfHeight + _lineWidth, 0.0), paintMain);
  }

  ///绘制文字
  void drawWords(Canvas canvas, Size size) {
    ///隐患整改率
    TextPainter titlePainter = new TextPainter();
    titlePainter.textDirection = TextDirection.ltr;

    if ("0" == _jige) {
      titlePainter.text = new TextSpan(
          text: _text,
          style: new TextStyle(
            color: Color(0xffFA5050),
            fontSize: 18,
          ));
//      paintZhen.color=Colors.red;
    } else {
      titlePainter.text = new TextSpan(
          text: _text,
          style: new TextStyle(
            color: SQColor.theme_color,
            fontSize: 18,
          ));
//      paintMain.color=Colors.blue;
    }

    titlePainter.layout();
    double titlePainterX = -titlePainter.size.width / 2;

    /// X轴 在文字中间
    double titlePainterY = (_lineWidth - titlePainter.size.height + 30)
        .toDouble(); //-((150-45-titlePainter.height));

    titlePainter.paint(canvas, new Offset(titlePainterX, titlePainterY));

    /// 显示的百分比数字
    TextPainter textPainter = new TextPainter();
    textPainter.textDirection = TextDirection.ltr;

    if ("0" == _jige) {
      textPainter.text = new TextSpan(
          text: formatNum(number_text, 2).toString() + '分',
          style: new TextStyle(
            color: Color(0xffFA5050),
            fontSize: 34,
          ));
//      paintZhen.color=Colors.red;
    } else {
      textPainter.text = new TextSpan(
          text: formatNum(number_text, 2).toString() + '分',
          style: new TextStyle(
            color: SQColor.theme_color,
            fontSize: 34,
          ));
//      paintMain.color=Colors.blue;
    }

    textPainter.layout();
    double textStarPositionX = -textPainter.size.width / 2;

    /// X轴 在文字中间
    double textStarPositionY =
        -(_lineWidth - textPainter.size.height + titlePainter.size.height + 50)
            .toDouble();

    textPainter.paint(canvas, new Offset(textStarPositionX, textStarPositionY));
    canvas.save();
  }

  String formatNum(double num, int postion) {
    if ((num.toString().length - num.toString().lastIndexOf(".") - 1) <
        postion) {
      //小数点后有几位小数
      return (num.toStringAsFixed(postion)
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    } else {
      return (num.toString()
          .substring(0, num.toString().lastIndexOf(".") + postion + 1)
          .toString());
    }
  }
}

class DashJieGuoboard extends StatefulWidget {
  double number;
  String text;
  String jige = "0";

  DashJieGuoboard({Key key, this.number, this.text, this.jige})
      : super(key: key);
  @override
  DashBoardState createState() => DashBoardState();
}

class DashBoardState extends State<DashJieGuoboard>
    with SingleTickerProviderStateMixin {
  Animation<double> animation;
  AnimationController animationController;
  VoidCallback _voidCallback;
  double number;
  String text;
  double numberText0;

  @override
  void initState() {
    animationController = new AnimationController(
        duration: const Duration(milliseconds: 1000), vsync: this);
    initAnimation(0, widget.number);
    animationController.forward();

    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    animationController.dispose();
    super.dispose();
  }

  void initAnimation(double old, double newPercentage) {
    numberText0 = widget.number;
    animation =
        new Tween(begin: old, end: newPercentage).animate(animationController);

    animation.addListener(_voidCallback = () {
      if (mounted) {
        setState(() {
          double value = animation.value;
          number = value;
        });
      }
    });

    animation.addStatusListener((animationStatus) {
      if (animationStatus == AnimationStatus.completed) {
        animation.removeListener(_voidCallback);
        animationController.reset();
      } else if (animationStatus == AnimationStatus.forward) {}
    });
  }

  @override
  Widget build(BuildContext context) {
    if (numberText0 != widget.number) {
      initAnimation(0, widget.number);
      animationController.forward();
      return new Container();
    }
    return new Container(
      height: 100,
      margin: EdgeInsets.fromLTRB(0, 8, 0, 0),
      width: ScreenUtil.getScreenW(context),
      alignment: Alignment.center,
      child: CustomPaint(
          size: new Size(250.0, 200.0),
          painter: DashBoardIndicatorPainter(number, widget.text, widget.jige)),
    );
  }
}

class DashBoardIndicatorPainter extends CustomPainter {
  double number;
  String text;
  String jige = "0";
  bool isfastLoad = true;
  DashBoardTablePainter _painter = new DashBoardTablePainter();
  DashBoardIndicatorPainter(this.number, this.text, this.jige);

  @override
  void paint(Canvas canvas, Size size) {
    // TODO: implement paint
    try {
      if (number != null) {
        canvas.drawPicture(_painter.getBackGround(number, text, jige));
      }
    } catch (e) {
      print(e);
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }
}
